# coding:utf-8
# 决策树算法
from sklearn import decomposition
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.feature_extraction import DictVectorizer
import pandas as pd


def decision():
    """
    决策树对泰坦尼克号进行预测生死
    :return: None
    """
    # 获取数据
    titan = pd.read_csv("G:/学习教程/人工智能/测试数据文件夹/taitannc.txt")

    # 处理数据，找出特征值和目标值
    x = titan[['pclass', 'age', 'sex']]

    y = titan['survived']

    print(x)
    # 缺失值处理
    x['age'].fillna(x['age'].mean(), inplace=True)

    # 分割数据集到训练集合测试集
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)

    # 进行处理（特征工程）特征-》类别-》one_hot编码
    dict = DictVectorizer(sparse=False)
    x_train = dict.fit_transform(x_train.to_dict(orient="records"))

    # print(dict.get_feature_names())

    x_test = dict.transform(x_test.to_dict(orient="records"))

    # print(x_train)

    # 使用网格搜索和交叉验证

    # 用决策树进行预测
    # dec = DecisionTreeClassifier()
    # # 使用网格搜索和交叉验证
    # params={'max_depth': [2,3,4,5,6]}
    # gs=GridSearchCV(dec,params,cv=5)
    # gs.fit(x_train,y_train)
    # print("预测的准确率：", gs.score(x_test,y_test))
    # print("最优参数匹配:",gs.best_params_)
    # print("最好的训练结果:",gs.best_score_)
    # print("计算结果详情:", gs.cv_results_)

    # dec.fit(x_train, y_train)
    # # 预测准确率
    # print("预测的准确率：", dec.score(x_test, y_test))
    # print(dict.get_feature_names())
    #
    # # 导出决策树的结构
    # export_graphviz(dec, out_file="./tree.dot", feature_names=['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male'])



    # 随机森林进行预测（比较准确的一种实现方式） （超参数调优）
    rf = RandomForestClassifier(n_jobs=-1)

    param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [4,5, 8, 15, 25]}

    # 网格搜索与交叉验证
    gc = GridSearchCV(rf, param_grid=param, cv=2)

    gc.fit(x_train, y_train)

    print("准确率：", gc.score(x_test, y_test))

    print("查看选择的参数模型：", gc.best_params_)
    print('查看所有拟合器：',gc.estimator)

    return None

if __name__ == '__main__':
    decision()